package cn.tedu.tmall.passport.controller;

import cn.tedu.tmall.common.pojo.security.CurrentPrincipal;
import cn.tedu.tmall.passport.pojo.vo.UserLoginResultVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/test")
@Api(tags = "02. 测试访问")
public class TestController {

    @GetMapping("/authenticated")
    @ApiOperation("需要通过认证的请求")
    @ApiOperationSupport(order = 100)
    public Object authenticated() {
        return "需要通过认证的请求，访问成功！";
    }

    @GetMapping("/principal")
    @ApiOperation("获取当事人信息")
    @ApiOperationSupport(order = 200)
    public Object principal(@ApiIgnore @AuthenticationPrincipal CurrentPrincipal principal) {
        return principal;
    }

    @GetMapping("/preAuthorize")
    @PreAuthorize("hasAuthority('/account/user/delete')")
    @ApiOperation("检查权限（删除账号）")
    @ApiOperationSupport(order = 300)
    public Object preAuthorize() {
        return "检查权限，通过！";
    }

    @GetMapping("/session")
    @ApiOperation("【已过期】获取Session中的数据")
    @ApiOperationSupport(order = 910)
    @Deprecated
    public Object session(@ApiIgnore HttpSession session) {
        Object loginResult = session.getAttribute("loginResult");
        if (loginResult == null) {
            return "你还没有登录，请先登录！";
        }
        return loginResult;
    }

    @GetMapping("/check-authority")
    @ApiOperation("【已过期】基于Session检查权限")
    @ApiOperationSupport(order = 920)
    @Deprecated
    public Object checkAuthority(@ApiIgnore HttpSession session) {
        Object object = session.getAttribute("loginResult");
        if (object == null) {
            return "你还没有登录，请先登录！";
        }

        UserLoginResultVO loginResult = (UserLoginResultVO) object;
        List<String> authorities = loginResult.getAuthorities();

        // 假设当前访问需要 /admin 权限
        if (!authorities.contains("/admin")) {
            return "您当前登录的账号无此操作权限！";
        }

        return "检查权限通过！";
    }

}
